<?php
/**
 * Created by PhpStorm.
 * User: robot
 * Date: 2018-04-18
 * Time: 22:59
 */
namespace app\admin\controller;
use app\base\BaseController;
use app\base\model\Sort as SortModel;
use think\Request;
class Sort extends BaseController
{
    /***
     * 输出分类管理页面视图
     * @return mixed
     */
    public function index()
    {
        $this->assign('title', '分类管理');
        return $this->fetch();
    }
    /***
     * 输出管理页面ajax数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ajax()
    {
        $request = Request::instance();
        if (!$request->isAjax()) {
            return ['code'=>-1,'msg'=>'请求方式错误'];
        }
        $sort = new SortModel();
        $limit = $request->param('limit');
        $offset = $limit * $request->param('page')-$limit;

        $total = $sort->count('sortid');
        $data = $sort->limit($offset,$limit)->select();
        return ['code' => 0, 'msg' => '', 'count' => $total, 'data' => $data];
    }
    /***
     * 删除分类接口
     * @return array
     */
    public function dell()
    {
        $request = Request::instance();
        $sortid = $request->has('sortid')?$request->param('sortid'):false;
        if (!$sortid) {
            return ['code' => -1, 'msg' => '分类id未找到'];
        }

        if (SortModel::destroy($sortid)) {
            return ['code' => 1, 'msg' => '删除成功'];
        } else {
            return ['code' => -1, 'msg' => '删除失败'];
        }
    }
    /***
     * 添加分类
     * @return array
     */
    public function addsort()
    {
        $request = Request::instance();
        $sortname = $request->has('sortname')?$request->param('sortname'):false;
        if (!$sortname) {
            return ['code' => -1, 'msg' => '请输入分类名'];
        }

        SortModel::create([
            'sortname' => $sortname
        ]);
        return ['code'=>1,'msg'=>'添加成功'];
    }
    /***
     * 编辑分类
     * @return array
     */
    public function editsort()
    {
        $request = Request::instance();
        $sortid = $request->has('sortid')?$request->param('sortid'):false;
        $sortname = $request->has('sortname')?$request->param('sortname'):false;
        if (!$sortid && $sortname) {
            return ['code' => -1, 'msg' => '参数错误'];
        }
        if (SortModel::where('sortid',$sortid)->update(['sortname'=>$sortname])) {
            return ['code'=>1,'msg'=>'修改成功'];
        } else {
            return ['code'=>-11,'msg'=>'修改失败'];
        }
    }
}